package com.yonyou.pmclouds.team.processor;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseVO;
import com.yonyou.pmclouds.team.mapper.TeamEnterpriseMapper;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TeamEnterpriseInsertCheck implements MultiProcessor<TeamEnterpriseVO> {
    private TeamEnterpriseMapper mapper;

    public TeamEnterpriseInsertCheck(TeamEnterpriseMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void process(TeamEnterpriseVO[] vos, TeamEnterpriseVO[] origs) throws BusinessException {
        // 校验企业的唯一性
        if (ArrayUtils.isEmpty(vos)) {
            return;
        }
        Set<String> allEnts = new HashSet<>();
        TeamEnterpriseVO[] ents = mapper.queryByProject(vos[0].getPkProject());
        for (TeamEnterpriseVO ent : ents) {
            if (ent.getPkEnterprise() == null) {
                throw new IllegalArgumentException();
            }
            allEnts.add(ent.getPkEnterprise());
        }
        List<TeamEnterpriseVO> duplicates = new ArrayList<>();
        for (TeamEnterpriseVO ent : vos) {
            if (!allEnts.add(ent.getPkEnterprise())) {
                duplicates.add(ent);
            }
        }
        //  构造异常
        if (duplicates.isEmpty()) {
            return;
        }
        BusinessException ex = new BusinessException();
        ex.addInfo("dupCount", Integer.toString(duplicates.size()));
        for (int i = 0; i < duplicates.size(); i++) {
            final TeamEnterpriseVO teamEnterpriseVO = duplicates.get(i);
            ex.addInfo("dupKey" + i, teamEnterpriseVO.getPkEnterprise());
            ex.addInfo("dupRole" + i, Integer.toString(teamEnterpriseVO.getEntRole()));
        }
        throw ex;
    }
}
